package com.geekstudy.week2.configuration;


import javax.servlet.ServletRequest;
import java.util.*;

public class DemoServletRequestConfiguration {

    private ServletRequest servletRequest;


    public DemoServletRequestConfiguration(ServletRequest servletRequest) {
        this.servletRequest = servletRequest;
    }

    public List<String> parameterNameList() {
        List<String> paramList = new ArrayList<String>();

        Map<String, String[]> parameterMap = servletRequest.getParameterMap();
        if(parameterMap != null && !parameterMap.isEmpty()) {
            paramList.addAll(parameterMap.keySet());
        }

        return paramList;
    }

    public Map<String, String> parameterFlatMap() {
        Map<String, String> parameterMap = new LinkedHashMap<String, String>();
        Map<String, String[]> originParameterMap = servletRequest.getParameterMap();
        if(originParameterMap != null && !originParameterMap.isEmpty()) {
            for(String parameterName : originParameterMap.keySet()) {
                String[] valueArray = originParameterMap.get(parameterName);
                if(valueArray == null || valueArray.length == 0) {
                    parameterMap.put(parameterName, "");
                } else if(valueArray.length == 1) {
                    parameterMap.put(parameterName, valueArray[0]);
                } else if(valueArray.length > 1) {
                    parameterMap.put(parameterName, Arrays.asList(valueArray).toString());
                }
            }
        }

        return parameterMap;
    }

}
